package xyz.jiang.gateway.utils;


import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.jiang.gateway.filter.TokenFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


@Data
@Component
public class PathWhiteListChecker {

    private static TokenFilter tokenFilter;

    private static List<Pattern> patterns;

    @Autowired
    public static void setTokenFilter(TokenFilter tokenFilter) {
        xyz.jiang.gateway.utils.PathWhiteListChecker.tokenFilter = tokenFilter;
    }

    public PathWhiteListChecker(TokenFilter tokenFilter) {
        patterns = new ArrayList<>();
        List<String> whiteList = tokenFilter.getWhiteList();

        for (String pattern : whiteList) {
            // 直接跳过空字符串的规则
            if (pattern == null || pattern.isEmpty()) {
                continue;
            }
            patterns.add(compilePattern(pattern));
        }
    }

    public static boolean isAllowed(String path) {
        String normalizedPath = normalizePath(path);
        if (normalizedPath.isEmpty()) {
            return false;
        }
        for (Pattern pattern : patterns) {
            if (pattern.matcher(normalizedPath).matches()) {
                return true;
            }
        }
        return false;
    }

    private static String normalizePath(String path) {
        if (path == null || path.isEmpty()) {
            return "";  // 空路径保持为空
        }
        // 标准化路径：替换多个斜杠为单个，确保以/开头
        String normalized = path.replaceAll("/+", "/");
        if (!normalized.startsWith("/")) {
            normalized = "/" + normalized;
        }
        return normalized;
    }

    private Pattern compilePattern(String pattern) {
        String regex = convertToRegex(pattern);
        return Pattern.compile(regex);
    }

    private String convertToRegex(String pattern) {
        // Step 1: 处理双星号通配符 **
        String temp = pattern.replace("**", "__DOUBLE_STAR__");

        // Step 2: 转义正则特殊字符
        String escaped = temp.replaceAll("([\\\\\\.\\[\\{\\(\\+\\?\\^\\$\\|\\]])", "\\\\$1");

        // Step 3: 恢复双星号为 .*
        String regexWithDoubleStar = escaped.replace("__DOUBLE_STAR__", ".*");

        // Step 4: 精准替换单星号 *（排除 .* 中的 *）
        String regexWithSingleStar = regexWithDoubleStar.replaceAll("(?<!\\.)\\*", "[^/]*");

        // Step 5: 完全匹配
        return "^" + regexWithSingleStar + "$";
    }
}
